/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package org.apache.myfaces.test.webapp.api;

import org.apache.myfaces.test.webapp.api.tester.WebappTester;

import java.util.*;

/**
 * @author Cosmin Martinconi, 06.08.2010
 */
public class ResourceFinder {

    public static final String WEBAPP_TESTER = WebappTester.class.getName();
    public static final String WEBAPP_TEST_CONFIGURATOR = WebappTestConfigurator.class.getName();

    private static Map<String, Object> registeredResources = new HashMap<String, Object>();

    public static Object getResource(String resourceName) {
        if (resourceName == null) {
            throw new NullPointerException("resourceClass may not be null");
        }

        if ((!registeredResources.containsKey(resourceName)) && WEBAPP_TEST_CONFIGURATOR.equals(resourceName)) {
            WebappTestConfigurator config = ServiceLoader.load(WebappTestConfigurator.class).iterator().next();

            setResource(WEBAPP_TEST_CONFIGURATOR, config);
        }

        if (!registeredResources.containsKey(resourceName)) {
            throw new IllegalArgumentException("no resource " + resourceName + " configured for this application.");
        } else {
            return registeredResources.get(resourceName);
        }
    }

    public static void setResource(String resourceName, Object implObj) {

        registeredResources.put(resourceName, implObj);
    }
}
